package com.edu.labmanager.controller;


import com.edu.labmanager.entity.Term;
import com.edu.labmanager.service.ITermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 学期表，存储学校的学期安排信息 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-15
 */
@Controller
@RequestMapping("/term")
public class TermController {

    @Autowired
    private ITermService termService;

    // 列表页
    @GetMapping("/")
    @PreAuthorize("hasRole('admin')")
    public String listTerms(Model model) {
        List<Term> terms = termService.list();
        model.addAttribute("terms", terms);
        return "term-list";
    }

    // 新增页面
    @GetMapping("/add")
    @PreAuthorize("hasRole('admin')")
    public String showAddForm(Model model) {
        model.addAttribute("term", new Term());
        return "term-form";
    }

    // 提交新增
    @PostMapping("/add")
    @PreAuthorize("hasRole('admin')")
    public String addTerm(@ModelAttribute Term term) {
        termService.save(term);
        return "redirect:/term/";
    }

    // 编辑页面
    @GetMapping("/edit/{id}")
    @PreAuthorize("hasRole('admin')")
    public String showEditForm(@PathVariable Integer id, Model model) {
        Term term = termService.getById(id);
        model.addAttribute("term", term);
        return "term-form";
    }

    // 提交更新
    @PostMapping("/update")
    @PreAuthorize("hasRole('admin')")
    public String updateTerm(@ModelAttribute Term term) {
        termService.updateById(term);
        return "redirect:/term/";
    }

    // 删除学期
    @GetMapping("/delete/{id}")
    @PreAuthorize("hasRole('admin')")
    public String deleteTerm(@PathVariable Integer id) {
        termService.removeById(id);
        return "redirect:/term/";
    }
}